/**
 *	\file CDSQPlayer.cpp
 *  
 *  \section desc_sec Description
 *  Description
 *  
 *  \if copyright
 *  	Copyright 2008 Jeffrey Zhang. All rights reserved.
 *  \endif
 *  
 *  \section hist_sec Change History:
 *  	-	2/11/08		Jeffrey Zhang		Created this file
 *  
 *  <hr>
 *  \addtogroup AKCPP
 *  @{
 */

#include "AKCommon.h"
#include "CDSQPlayer.h"
#include "CDSQTTHHEngine.h"
#include "CDSQBoard.h"

CDSQPlayer::CDSQPlayer(AKSideIndex aSide, unsigned int aNumOfSides)
	:PARENT(aSide, aNumOfSides)
{
	m_pBoard = new CDSQBoard();
	m_pEngine = new CDSQTTHHEngine();
	m_pEngine->SetSearchDepth(Professinal);
}
CDSQPlayer::~CDSQPlayer(void)
{
}

// Search depth
void CDSQPlayer::setSearchDepth(Level newDepth)
{
	m_pEngine->SetSearchDepth(newDepth);
}

Level CDSQPlayer::getSearchDepth() const
{
	return m_pEngine->GetSearchDepth();
}

//	State
void CDSQPlayer::backToInitialState()
{
	m_pBoard->backToInitialState();
	m_pEngine->backToInitialState();

	lastMove = AKZeroMove;
}

bool CDSQPlayer::performMove(const AKMove newMove)
{
	PieceMove cmMove;
	int i,j,x,y;
	
	x = newMove.srcCell%9;
	y = newMove.srcCell/9;
	
	i = newMove.dstCell/9;
	j = newMove.dstCell%9;
	
	if( !m_pBoard->IsValidMove(x, y, j, i) )
		return false;
	else
	{
		cmMove.From.x = x;
		cmMove.From.y = y;
		cmMove.To.x = j;
		cmMove.To.y = i;
	}
	
	undotype = m_pBoard->MakeMove(&cmMove);
	
	lastMove = newMove;
	
	return true;
}

const AKMove CDSQPlayer::getBestMove()
{
	//hasAlternative = true;
	return m_pEngine->SearchAGoodMove(m_pBoard, PARENT::side);
}

const AKMove CDSQPlayer::getAlternativeMove()
{
	/*if( hasAlternative )
		return ToAKMove(m_cmBetterMove);
	else*/
		return AKZeroMove;
}

bool CDSQPlayer::canUndo()
{
	if (lastMove.piece != NSNotFound && lastMove.dstCell != NSNotFound)
		return true;
	else
		return false;
}
bool CDSQPlayer::undo()
{
	if (canUndo())
	{
		// Only one time of undo is supported here.
		PieceMove cmMove;
		
		cmMove.From.x = lastMove.srcCell%9;
		cmMove.From.y = lastMove.srcCell/9;
		cmMove.To.y = lastMove.dstCell/9;
		cmMove.To.x = lastMove.dstCell%9;
		
		m_pBoard->UnMakeMove(&cmMove,undotype);
		lastMove = AKZeroMove;
		return true;
	}
	else
		return false;
}

void CDSQPlayer::setSearchEngine(CAlgSearchEngine* pEngine)
{
	if(pEngine)
		m_pEngine = pEngine;
}

CAlgSearchEngine* CDSQPlayer::getSearchEngine()
{
	return m_pEngine;
}